<template>
  <div class="page-container">
    <div class="address-grid">
      <!-- 新增地址卡片 -->
      <el-card class="add-address-card" shadow="hover" @click="showAddAddressDialog">
        <div class="add-address-content">
          <el-icon><Plus /></el-icon>
          <span>新增地址</span>
        </div>
      </el-card>

      <!-- 地址列表 -->
      <el-card 
        v-for="address in addresses" 
        :key="address.id" 
        class="address-card" 
        :class="{ 'default-address': address.isDefault }"
        shadow="hover"
      >
        <template #header>
          <div class="card-header">
            <span>{{ address.isDefault ? '默认地址' : '收货地址' }}</span>
            <el-tag v-if="address.isDefault" type="success" effect="dark" size="small">默认</el-tag>
          </div>
        </template>
        <div class="address-details">
          <p>{{ address.address }}</p>
        </div>
        <div class="address-actions">
           <el-button 
            v-if="!address.isDefault" 
            type="primary" 
            text
            @click="setDefaultAddress(address)"
          ><el-icon><Star /></el-icon>设为默认</el-button>
          <el-button 
            type="danger" 
            text 
            @click="deleteAddress(address)"
          ><el-icon><Delete /></el-icon>删除</el-button>
        </div>
      </el-card>

       <el-empty v-if="!addresses.length && !loading" description="您还没有添加任何地址" :image-size="150"></el-empty>
    </div>

    <!-- 新增/编辑地址对话框 -->
    <el-dialog
      v-model="addressDialogVisible"
      :title="isEdit ? '编辑地址' : '新增地址'"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="addressFormRef"
        :model="addressForm"
        :rules="addressRules"
        label-width="100px"
      >
        <el-form-item label="详细地址" prop="address">
          <el-input
            v-model="addressForm.address"
            type="textarea"
            :rows="3"
            placeholder="请输入详细地址"
          />
        </el-form-item>
<!--        <el-form-item label="设为默认">-->
<!--          <el-switch v-model="addressForm.isDefault" />-->
<!--        </el-form-item>-->
        <el-form-item label="设为默认">
          <el-radio-group v-model="addressForm.isDefault">
            <el-radio value="1">默认</el-radio>
            <el-radio value="0">非默认</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addressDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveAddress" :loading="submitting">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Star, Delete } from '@element-plus/icons-vue'
import {useUserStore} from "@/pinia/index.js";
import axios from "axios";

// 地址数据
const loading = ref(false)
const addresses = ref([
  {
    id: null,
    address: '',
    isDefault: null,
    createdAt: ''
  },
])
var userStore = useUserStore();
// 新增/编辑地址相关
const addressDialogVisible = ref(false)
const isEdit = ref(false)
const addressFormRef = ref(null)
const addressForm = reactive({
  userId:userStore.getUserId,
  address: '',
  isDefault: 0
})
const submitting = ref(false)

const addressRules = {
  address: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { min: 5, message: '地址长度不能小于5个字符', trigger: 'blur' }
  ]
}
const getAddressAll=(userId)=>{
  axios({
    url:"/UserApi/user/addressSel",
    method:"post",
    params:{userId:userId}
  }).then(res=>{
    addresses.value=res.data
    console.log(res.data)
  })
}
getAddressAll(userStore.getUserId);

// 显示新增地址对话框
const showAddAddressDialog = () => {
  isEdit.value = false
  addressFormRef.value?.resetFields()
  addressForm.id = null
  addressForm.address = ''
  addressForm.isDefault = false
  addressDialogVisible.value = true
}

// 编辑地址
const editAddress = (row) => {
  isEdit.value = true
  addressForm.id = row.id
  addressForm.address = row.address
  addressForm.isDefault = row.isDefault
  addressDialogVisible.value = true
}
// 添加地址
const saveAddress = async () => {
  axios({
    url:"/UserApi/user/addressAdd",
    method:"post",
    data:addressForm
  }).then(res=>{
    ElMessage.success('地址创建成功')
    addressDialogVisible.value=false
    getAddressAll(userStore.getUserId)
  })
}
// 保存地址
// const saveAddress = async () => {
//   if (!addressFormRef.value) return
//
//   await addressFormRef.value.validate((valid) => {
//     if (valid) {
//       submitting.value = true
//       // TODO: 实现保存地址逻辑
//       setTimeout(() => {
//         ElMessage.success(isEdit.value.value ? '地址修改成功' : '地址添加成功')
//         addressDialogVisible.value = false
//         submitting.value = false
//       }, 1000)
//     }
//   })
// }

// 设置默认地址
const setDefaultAddress = (row) => {
  ElMessageBox.confirm(
    '确定要将该地址设为默认地址吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    axios({
      url: "/UserApi/user/moRen",
      method: "post",
      params: { id: row.id }
    }).then(res=>{
      ElMessage.success('设置成功')
      getAddressAll(userStore.getUserId)
    })
    // TODO: 实现设置默认地址逻辑

  }).catch(() => {})
}

// 删除地址
const deleteAddress = (row) => {
  ElMessageBox.confirm(
    '确定要删除该地址吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    axios({
      url: "/UserApi/user/addressDel",
      method: "post",
      params: { id: row.id }
    }).then(res=>{
      ElMessage.success('删除成功')
      getAddressAll(userStore.getUserId)
    })
    // TODO: 实现删除地址逻辑

  }).catch(() => {})
}
</script>

<style scoped>
.page-container {
  padding: 24px;
  background-color: #f0f2f5;
  min-height: 100vh;
}

.address-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 24px;
}

.address-card, .add-address-card {
  border-radius: 12px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

.address-card:hover, .add-address-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0,0,0,0.1);
}

.address-card.default-address {
  border-color: #67c23a;
  background-color: #f0f9eb;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 1rem;
  font-weight: 600;
  color: #303133;
}

.address-details {
  padding: 16px 0;
  min-height: 60px;
  color: #606266;
  font-size: 0.95rem;
  line-height: 1.6;
}

.address-actions {
  padding-top: 12px;
  border-top: 1px solid #e4e7ed;
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.add-address-card {
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  min-height: 210px;
  border-style: dashed;
}

.add-address-content {
  text-align: center;
  color: #909399;
}

.add-address-content .el-icon {
  font-size: 48px;
  margin-bottom: 16px;
  display: block;
}

.add-address-content span {
  font-size: 1.1rem;
  font-weight: 500;
}

:deep(.el-dialog) {
  border-radius: 12px;
}

:deep(.el-dialog__header) {
  padding: 16px 24px;
  background-color: #f7f8fa;
  border-bottom: 1px solid #ebeef5;
  border-radius: 12px 12px 0 0;
}

:deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 500;
}

.el-button .el-icon {
  margin-right: 4px;
}
</style> 